package cn.lixufeng.org.service.impl;

import cn.lixufeng.basic.exception.BusinessException;
import cn.lixufeng.basic.service.impl.BaseServiceImpl;
import cn.lixufeng.org.domain.Employee;
import cn.lixufeng.org.domain.Shop;
import cn.lixufeng.org.mapper.EmployeeMapper;
import cn.lixufeng.org.mapper.ShopMapper;
import cn.lixufeng.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void settlement(Shop shop) {
        // 先验证：一是前端页面注册时两次输入的密码是否一致，二是检查用户名是否已经存在
        // 因为验证可能出现业务bug，所以要先新建一个业务异常
        Employee admin = shop.getAdmin();// 这个admin是前端想注册的admin而不是数据库中存在的
        if (!admin.getPassword().equals(admin.getConfirmPassword())) {
            throw new BusinessException("两次密码输入不一致！");
        }
        // 要验证用户名是否已经存在，这里的用户是指的数据库中已经存在的用户
        Employee employee = employeeMapper.findByUsername(admin.getUsername());
        if (employee != null) {
            throw new BusinessException("用户名已存在！");
        }
        // 保存商家管理员,并且返回自增id
        employeeMapper.add(admin);
        // 设置管理员，保存商家信息，并返回商家自增id
        shop.setAdmin(admin);
        shopMapper.add(shop);
        // 修改管理员的商家id
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);
    }
}
